#include "AffichageSDL.h"

static void initStructSDL(StructSDL* structSDL)
{
  structSDL->largeurEcran = 1024;
  structSDL->hauteurEcran = 768;
  structSDL->couleursEcran = 24;
  structSDL->fenetrePrincipale = NULL;
  structSDL->unitDist = 30;
  structSDL->xDepCarte = 4*structSDL->unitDist;
  structSDL->yDepCarte = 4*structSDL->unitDist;
  structSDL->hauteurCarte = 25;
  structSDL->largeurCarte = 51;
  structSDL->xVue = 1;
  structSDL->yVue = 1; 
  structSDL->zVue = 0;
  structSDL->xCaseActive = 0;
  structSDL->yCaseActive = 0;
  structSDL->zCaseActive = 0;
} 

void creerStructSDL(StructSDL** structSDL)
{
  *structSDL = (StructSDL*) malloc(sizeof(StructSDL));
  initStructSDL(*structSDL);
}

static void detruireStructSDL(StructSDL* structSDL)
{
  if(structSDL->fenetrePrincipale != NULL)
    SDL_FreeSurface(structSDL->fenetrePrincipale);
  if(structSDL->colonne != NULL)
    SDL_FreeSurface(structSDL->colonne);
  if(structSDL->entete != NULL)
    SDL_FreeSurface(structSDL->entete);
  if(structSDL->fond != NULL)
    SDL_FreeSurface(structSDL->fond);

  if(structSDL != NULL)
    free(structSDL);
}

static void blitteSurface( int x, int y, SDL_Surface* source, SDL_Surface* destination )
{
  SDL_Rect decalage;

  decalage.x = x;
  decalage.y = y;

  SDL_BlitSurface( source, NULL, destination, &decalage );
}

static void miseAJourTailles(StructSDL* structSDL)
{
  SDL_FreeSurface(structSDL->fenetrePrincipale);
  structSDL->fenetrePrincipale = SDL_SetVideoMode(structSDL->largeurEcran, structSDL->hauteurEcran, structSDL->couleursEcran, SDL_HWSURFACE|SDL_DOUBLEBUF|SDL_RESIZABLE);

}

static void affichageProductions(StructSDL* structSDL, Carte* carte, int i, int j)
{
 /*case active*/
  Uint32 colorkey;
  SDL_Surface* production = NULL;
 

  char lien[64] = "data/";
  char extension[] = ".bmp";
  char* chaineVar;


  SDL_Rect decalage;
  int tailleTuile;

  tailleTuile = structSDL->unitDist;
  /*paramètres de la carte*/
    
    chaineVar = getNomProdCaseCarte(carte, (i + structSDL->xVue - 1), (j + structSDL->yVue - 1), structSDL->zVue);

    if(chaineVar != NULL)
      {

	strcat(lien,chaineVar);
	strcat(lien,extension);
      
	production = SDL_LoadBMP(lien);
      
	if (production)
	  {
	    decalage.x = structSDL->xDepCarte + i*tailleTuile;
	    decalage.y = structSDL->yDepCarte + j*tailleTuile;
	  
	    colorkey = SDL_MapRGB( production->format, 0x00, 0xFF, 0xFF );
	  
	    SDL_SetColorKey( production, SDL_RLEACCEL | SDL_SRCCOLORKEY, colorkey );

	    blitteSurface(decalage.x, decalage.y, production, structSDL->fenetrePrincipale);
	  
	  }
	else
	  {
	    printf("Impossible d'ouvrir le bitmap de selection: %s\n", SDL_GetError());
	  }
      }
  SDL_FreeSurface(production);
}


void afficheCarte(StructSDL* structSDL, Carte* carte)
{
  int i,j;
  int x,y,z;
  int xMaxStructCarte;
  int yMaxStructCarte;
  SDL_Surface* bmpTerrain = NULL;
  SDL_Rect decalage;
  Terrain* terrainAffiche = NULL;
  char* representationTerrain = NULL;
  char* representationTerrainPrecedent = NULL;
  char representationHorsCarte[] = "data/neant.bmp";

  /*case active*/
  Uint32 colorkey;
  SDL_Surface* caseActive = NULL;

  /*paramètres de la carte*/
  int tailleTuile;

  xMaxStructCarte = getXCarte(carte)-1;
  yMaxStructCarte = getYCarte(carte)-1;
  tailleTuile = structSDL->unitDist;

  x = structSDL->xCaseActive - structSDL->xVue + 1;
  y = structSDL->yCaseActive - structSDL->yVue + 1;
  z = structSDL->zCaseActive;


  caseActive = SDL_LoadBMP("data/selection.bmp");
  if (caseActive)
    {
      
      colorkey = SDL_MapRGB( caseActive->format, 0x00, 0xFF, 0xFF );
      SDL_SetColorKey( caseActive, SDL_RLEACCEL | SDL_SRCCOLORKEY, colorkey );

      /* affichage des tuiles*/
      for(i=0; i<structSDL->largeurCarte; i++)
	{
	  for(j=0; j<structSDL->hauteurCarte; j++)
	    {
	      decalage.x = structSDL->xDepCarte + i*tailleTuile;
	      decalage.y = structSDL->yDepCarte + j*tailleTuile;


	      if((i + structSDL->xVue)<=0 || (i + structSDL->xVue)>xMaxStructCarte || (j + structSDL->yVue<=0) || (j+structSDL->yVue)>yMaxStructCarte)
		{
		  representationTerrain = representationHorsCarte;
		}
	      else
		{
		  terrainAffiche = getTerrainCaseCarte(carte, (i + structSDL->xVue - 1), (j+structSDL->yVue - 1),structSDL->zVue);
		  representationTerrain = getRepresentationTerrain(terrainAffiche);
		}


	      if(representationTerrainPrecedent == NULL || strcmp(representationTerrain,representationTerrainPrecedent) == 0)
		{
		  SDL_FreeSurface(bmpTerrain);

		  bmpTerrain = SDL_LoadBMP(representationTerrain);
		  if (!bmpTerrain)
		    {
		      printf("Impossible d'ouvrir le bitmap de terrain: %s\n", SDL_GetError());
		      break;
		    }
		}

	      /*on blitte la tuile*/
	      SDL_BlitSurface(bmpTerrain, 0, structSDL->fenetrePrincipale, &decalage );
	      
	      /*affichage des productions sur la carte*/
	      if((i + structSDL->xVue) > 0 && (i + structSDL->xVue + 1) < xMaxStructCarte-1 && (j + structSDL->yVue > 0) && (j+structSDL->yVue + 1) < yMaxStructCarte-1)
		affichageProductions(structSDL, carte, i, j);


	      representationTerrain = representationTerrainPrecedent;
	    }
	}


      /*on blitte la case active*/
	 
      if( (z == structSDL->zVue) && (x >= 0) && (x < structSDL->largeurCarte) && (y >= 0) && (y < structSDL->hauteurCarte) )
	{
	  decalage.x = structSDL->xDepCarte + x*tailleTuile;
	  decalage.y = structSDL->yDepCarte + y*tailleTuile;

	  blitteSurface(decalage.x, decalage.y, caseActive, structSDL->fenetrePrincipale);

	}
    
      SDL_FreeSurface(caseActive);
      if(bmpTerrain != NULL) SDL_FreeSurface(bmpTerrain);
    }
  else
    {
      printf("Impossible d'ouvrir le bitmap de selection: %s\n", SDL_GetError());
    }

}

static void affichageTextes(StructSDL* structSDL)
{
  int i,j;
  int boucle;
  Personnage* personnageTmp;

  char* font = "data/wonderland.ttf";
  char res[32];
  SDL_Surface *message = NULL; 
  Entrepot* reserves;
  Population* population;
  Caracteristiques* caracteristiques;

  boucle = 0;

  reserves = getReserves(structSDL->ville);
  population = structSDL->ville->population;

  /*=== Titres des entetes ===*/
  structSDL->font = TTF_OpenFont(font,40); 
  if( structSDL->font == NULL ) 
    { 
      printf("Erreur de chargement de la police de caractère %s",font); 
    } 
  structSDL->couleurTexte.r = 221;
  structSDL->couleurTexte.g = 221;
  structSDL->couleurTexte.b = 221;

  message = TTF_RenderText_Solid(structSDL->font, "        Entrepot                                  Ville", structSDL->couleurTexte);
  if( message == NULL )
    { 
      printf("Erreur de chargement du texte\n"); 
    } 
  blitteSurface( 10, 0, message, structSDL->fenetrePrincipale);
  TTF_CloseFont(structSDL->font);
  SDL_FreeSurface(message);

 /*=== Contenu de l'entrepot ===*/
  structSDL->font = TTF_OpenFont(font,30);

  sprintf(res,"   Biere: %d",getBiereEntr(reserves));
  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 10, 30, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

  sprintf(res,"   Houblon: %d",getHoublonEntr(reserves));
  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 160, 30, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

  sprintf(res, "   Bois: %d",getBoisEntr(reserves));
 message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 10, 60, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

  sprintf(res,"   Nourriture: %d",getNourritureEntr(reserves));
message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 160, 60, message, structSDL->fenetrePrincipale);
   SDL_FreeSurface(message);

  sprintf(res,"   Metal: %d",getMetalEntr(reserves));
message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 10, 90, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);


  /*=== Paramètres de la ville ===*/

  sprintf(res,"   Effectifs: %d",getEffectifTotal(population));
  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 400, 30, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

 sprintf(res,"   Moral: %d",getMoral(population));
  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 575, 30, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

 sprintf(res,"   Nombre d'affames: %d",getNbPersAffames(population));
  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 750, 30, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

    sprintf(res,"   Fecondite: %d",getFecondite(population));
  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
	  blitteSurface( 400, 60, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

	  sprintf(res, "   Mortalite: %d",getMortalite(population));
 message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 575, 60, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

  sprintf(res,"   Emigration: %d",getEmigration(population));
message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 400, 90, message, structSDL->fenetrePrincipale);
   SDL_FreeSurface(message);

  sprintf(res,"   Immigration: %d",getImmigration(population));
message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
  blitteSurface( 575, 90, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

  TTF_CloseFont(structSDL->font);


  /*============= Informations personnage actif =====================*/

  structSDL->font = TTF_OpenFont(font,30);
	
  message = TTF_RenderText_Solid(structSDL->font, " Personnage", structSDL->couleurTexte);
  blitteSurface(0,180, message, structSDL->fenetrePrincipale);
  TTF_CloseFont(structSDL->font);
  SDL_FreeSurface(message);

  structSDL->font = TTF_OpenFont(font,24);

  message = TTF_RenderText_Solid(structSDL->font, " PV:", structSDL->couleurTexte);
  blitteSurface(0,250, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

  message = TTF_RenderText_Solid(structSDL->font, " Minage:", structSDL->couleurTexte);
  blitteSurface(0,320, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

  message = TTF_RenderText_Solid(structSDL->font, " Bucheronnage:", structSDL->couleurTexte);
  blitteSurface(0,390, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

  message = TTF_RenderText_Solid(structSDL->font, " Artisanat:", structSDL->couleurTexte);
  blitteSurface(0,460, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);
  
  message = TTF_RenderText_Solid(structSDL->font, " Faim:", structSDL->couleurTexte);
  blitteSurface(0,530, message, structSDL->fenetrePrincipale);
  SDL_FreeSurface(message);

  TTF_CloseFont(structSDL->font);


  for(i=0; i<structSDL->largeurCarte; i++)
    {
      for(j=0; j<structSDL->hauteurCarte; j++)
	{
	  personnageTmp = structSDL->ville->population->dernierPersonnage;
				
	  while(personnageTmp != NULL && boucle == 0)
	    { 
			    
	      if( (getZPers(personnageTmp) == structSDL->zCaseActive) && (getXPers(personnageTmp) == structSDL->xCaseActive) && (getYPers(personnageTmp) == structSDL->yCaseActive))
		{
		  caracteristiques =  getCarac(personnageTmp);


		  structSDL->font = TTF_OpenFont(font,24);
	 
		  sprintf(res,"  %d",getPV(caracteristiques));
		  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
		  blitteSurface(0,280, message, structSDL->fenetrePrincipale);
		  SDL_FreeSurface(message);
  
		  sprintf(res,"  %d",getMinage(caracteristiques));
		  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
		  blitteSurface( 0, 350, message, structSDL->fenetrePrincipale);
		  SDL_FreeSurface(message);

		  sprintf(res,"  %d",getBucheronnage(caracteristiques));
		  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
		  blitteSurface( 0, 420, message, structSDL->fenetrePrincipale);
		  SDL_FreeSurface(message);

		  sprintf(res,"  %d",getArtisanat(caracteristiques));
		  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
		  blitteSurface( 0, 490, message, structSDL->fenetrePrincipale);
		  SDL_FreeSurface(message);

		  sprintf(res,"  %d",getFaim(caracteristiques));
		  message = TTF_RenderText_Solid(structSDL->font, res, structSDL->couleurTexte);
		  blitteSurface( 0, 560, message, structSDL->fenetrePrincipale);
		  SDL_FreeSurface(message);
  
		  TTF_CloseFont(structSDL->font);

		  boucle = 1;
		}
	      personnageTmp = personnageTmp->personnagePrecedent;
	    }
			    
	}
    }


}

void avanceDansTrajet(Personnage* personnage)
{
  int x,y,z;
  CalculTrajet* tmp;
  if(personnage->trajet->caseCarte != NULL)
    {

      x = getXCase(personnage->trajet->caseCarte);
      y = getYCase(personnage->trajet->caseCarte);
      z = getZCase(personnage->trajet->caseCarte);
    
      setXPers(personnage, x);
      setYPers(personnage, y);
      setZPers(personnage, z);

      printf("pers %d %d %d\n",x,y,z);

      if(personnage->trajet->calcSuivant == NULL)  
	{
	  free(personnage->trajet);
	  personnage->trajet = NULL;
	}
      else
	{
	  tmp = personnage->trajet->calcSuivant;
	  free(personnage->trajet);
	  personnage->trajet = tmp;
	}
    }
  else
    personnage->trajet = NULL;
}

void affichagePersonnages(StructSDL* structSDL, Carte* carte)
{
  Personnage* personnageTmp;
  int x,y,z, tailleTuile;
  Entrepot *pstock = getReserves(structSDL->ville);
  TabComp *ptabComp = getTabCompPop(structSDL->ville->population);


  SDL_Rect decalage;

  /*case personnage*/
  Uint32 colorkey;
  SDL_Surface* casePerso = NULL;

  personnageTmp = structSDL->ville->population->membres;
  tailleTuile = structSDL->unitDist;

  casePerso = SDL_LoadBMP("data/nain.bmp");

  if (casePerso)
    {
      colorkey = SDL_MapRGB( casePerso->format, 0x00, 0xFF, 0xFF );
      SDL_SetColorKey( casePerso, SDL_RLEACCEL | SDL_SRCCOLORKEY, colorkey );

      personnageTmp = structSDL->ville->population->dernierPersonnage;

      while(personnageTmp != NULL)
	{
	  if(personnageTmp->trajet != NULL)
	    avanceDansTrajet(personnageTmp);
	  else
		{
		   changementComportementPers(personnageTmp, carte, ptabComp, pstock);
		}

	  x = getXPers(personnageTmp) - structSDL->xVue + 1;
	  y = getYPers(personnageTmp) - structSDL->yVue + 1;
	  z = getZPers(personnageTmp);


	  if( (z == structSDL->zVue) && (x >= 0) && (x < structSDL->largeurCarte) && (y >= 0) && (y < structSDL->hauteurCarte) )
	    {

	      decalage.x = structSDL->xDepCarte + x*tailleTuile;
	      decalage.y = structSDL->yDepCarte + y*tailleTuile;

	      blitteSurface(decalage.x, decalage.y, casePerso, structSDL->fenetrePrincipale);

	    }

	  personnageTmp = personnageTmp->personnagePrecedent;

	}    
      SDL_FreeSurface(casePerso);
    }
  else
    {
      printf("Erreur de chargement du fichier personnage\n");
    }
}


void boucleEvenements(StructSDL* structSDL, Carte* carte, char* done)
{

  /*boucle de d'évenements*/
  SDL_Event event;
  int x,y, tailleTuile;
  int xPers, yPers, zPers;
  int i,j;
  int boucle;
  SDL_Rect decalage;
  Personnage* personnageTmp;

  tailleTuile = structSDL->unitDist;
  boucle = 0;

  while (SDL_PollEvent(&event))
    {
      /*écoute des évenements*/
      switch (event.type)
	{
	  /*sortie si l'on clique sur la croix de fermeture*/
	case SDL_QUIT:
	  *done = 1;
	  break;

	case SDL_VIDEORESIZE:
	  structSDL->largeurEcran = event.resize.w;
	  structSDL->hauteurEcran = event.resize.h;
	  miseAJourTailles(structSDL);
	  break;

	  /*les touches claviers sont scrutées*/
	case SDL_KEYDOWN:
	  {
	    switch (event.key.keysym.sym)
	      {

		/*sortie si esc est pressé*/
	      case SDLK_ESCAPE:
		*done = 1;
		break;

		/*changement de profondeur d'affichage*/
	      case SDLK_e:
		if(structSDL->zVue > 0)
		  structSDL->zVue--;
		break;

	      case SDLK_r:
		if(structSDL->zVue < 4)
		  structSDL->zVue++;
		break;

	      case SDLK_UP:
		structSDL->yVue--;
		break;

	      case SDLK_DOWN:
		structSDL->yVue++;
		break;

	      case SDLK_LEFT:
		structSDL->xVue--;
		break;

	      case SDLK_RIGHT:
		structSDL->xVue++;
		break;

	      default:
		break;

	      }
	    break;

	  case SDL_MOUSEBUTTONDOWN:
	    switch(event.button.button)
	      {
	      case SDL_BUTTON_LEFT:	      
		x = event.button.x;
		y = event.button.y;
		
		for(i=0; i<structSDL->largeurCarte; i++)
		  {
		    for(j=0; j<structSDL->hauteurCarte; j++)
		      {
			decalage.x = structSDL->xDepCarte + i*tailleTuile;
			decalage.y = structSDL->yDepCarte + j*tailleTuile;

			if( (x > decalage.x) && (x < decalage.x+tailleTuile) && (y > decalage.y) && (y < decalage.y+tailleTuile))
			  {
			    structSDL->xCaseActive = i + structSDL->xVue - 1;
			    structSDL->yCaseActive = j + structSDL->yVue - 1;
			    structSDL->zCaseActive = structSDL->zVue;
			  }
		      }
		  }
		break;

	      case SDL_BUTTON_RIGHT:	      
		x = event.button.x;
		y = event.button.y;
						
		for(i=0; i<structSDL->largeurCarte; i++)
		  {
		    for(j=0; j<structSDL->hauteurCarte; j++)
		      {
			decalage.x = structSDL->xDepCarte + (i+1)*tailleTuile;
			decalage.y = structSDL->yDepCarte + (j+1)*tailleTuile;

			/*caseTmp = getCaseCarte(carte,decalage.x,decalage.y,structSDL->zVue);
			if(getTraversableCase(caseTmp) == 0)
			{*/

			    if( (x > decalage.x) && (x < decalage.x+tailleTuile) && (y > decalage.y) && (y < decalage.y+tailleTuile))
			      {
				personnageTmp = structSDL->ville->population->dernierPersonnage;
				
				while(personnageTmp != NULL && boucle == 0)
				  { 
				    
				    if( (getZPers(personnageTmp) == structSDL->zCaseActive) && (getXPers(personnageTmp) == structSDL->xCaseActive) && (getYPers(personnageTmp) == structSDL->yCaseActive))
				      {
					
					structSDL->xCaseActive = i + structSDL->xVue;
					structSDL->yCaseActive = j + structSDL->yVue;
					xPers = getXPers(personnageTmp);
					yPers = getYPers(personnageTmp);
					zPers = getZPers(personnageTmp);

					personnageTmp->trajet = rechercheChemin(xPers, yPers, zPers, structSDL->xCaseActive, structSDL->yCaseActive, structSDL->zVue, carte);
					boucle = 1;
				      }
				    personnageTmp = personnageTmp->personnagePrecedent;

				  }
			      }
			    boucle = 0;
			
			
		      }
		  }
		break;
	      }
	  }
	}
    } /*fin de boucle d'évenements*/
}

static void affichePageTouches(StructSDL* structSDL)
{
  char done = 0;
  int largeur;
  
  SDL_Surface* dem;
  SDL_Surface* clicDroit;
  SDL_Surface* clicGauche;
  SDL_Surface* fleches;
  SDL_Surface*ER;

  SDL_Event event;
  
  char* font = "data/wonderland.ttf";
  SDL_Surface *message = NULL; 

  
  /*====================== Fond de la page de demarrage =====================*/

  dem = SDL_LoadBMP("data/demarrage.bmp");
  if (!dem)
    {
      printf("Unable to load bitmap: %s\n", SDL_GetError());
    }
  structSDL->pageDemarrage = SDL_DisplayFormat(dem);
  SDL_FreeSurface(dem);

clicDroit = SDL_LoadBMP("data/clicDroit.bmp");
  if (!clicDroit)
    {
      printf("Unable to load bitmap: %s\n", SDL_GetError());
    }

clicGauche = SDL_LoadBMP("data/clicGauche.bmp");
  if (!clicGauche)
    {
      printf("Unable to load bitmap: %s\n", SDL_GetError());
    }

fleches = SDL_LoadBMP("data/fleches.bmp");
  if (!fleches)
    {
      printf("Unable to load bitmap: %s\n", SDL_GetError());
    }

ER = SDL_LoadBMP("data/ER.bmp");
  if (!ER)
    {
      printf("Unable to load bitmap: %s\n", SDL_GetError());
    }


  while(done == 0)
    {
      largeur = structSDL->largeurEcran/2;

      /*effacer l'écran*/
      SDL_FillRect(structSDL->fenetrePrincipale, 0, SDL_MapRGB(structSDL->fenetrePrincipale->format, 0, 0, 0));
  
      /* chargement image de fond */
      blitteSurface(0,0,structSDL->pageDemarrage,structSDL->fenetrePrincipale);

      blitteSurface(largeur / 30,150,clicDroit,structSDL->fenetrePrincipale);
      blitteSurface(largeur / 30,300,clicGauche,structSDL->fenetrePrincipale);
      blitteSurface(largeur / 30,450,fleches,structSDL->fenetrePrincipale);
      blitteSurface(largeur / 30,600,ER,structSDL->fenetrePrincipale);



      /*========================= Texte de la page des commandes ============================*/

      /* 1ere taille de police */
      structSDL->font = TTF_OpenFont(font,100); 
      if( structSDL->font == NULL ) 
	{ 
	  printf("Erreur de chargement de la police de caractère %s",font); 
	} 
      structSDL->couleurTexte.r = 255;
      structSDL->couleurTexte.g = 255;
      structSDL->couleurTexte.b = 255;

      message = TTF_RenderText_Solid(structSDL->font, "Commandes du jeu", structSDL->couleurTexte);
      if( message == NULL )
	{ 
	  printf("Erreur de chargement du texte\n"); 
	} 
      blitteSurface(largeur/2 -50, 10, message, structSDL->fenetrePrincipale);
      TTF_CloseFont(structSDL->font);
      SDL_FreeSurface(message);

      /* 2eme taille de police */
      structSDL->font = TTF_OpenFont(font,40);

      message = TTF_RenderText_Solid(structSDL->font, "Utilisez le clic droit pour selectionner une case ou un nain", structSDL->couleurTexte);
      blitteSurface(largeur/3, 190, message, structSDL->fenetrePrincipale);
      SDL_FreeSurface(message);

message = TTF_RenderText_Solid(structSDL->font, "Utilisez le clic gauche pour selectionner l'arrivee du nain choisit", structSDL->couleurTexte);
      blitteSurface(largeur/3, 340, message, structSDL->fenetrePrincipale);
      SDL_FreeSurface(message);

message = TTF_RenderText_Solid(structSDL->font, "Utilisez les touches flechees pour vous deplacer dans la carte", structSDL->couleurTexte);
      blitteSurface(largeur/3, 490, message, structSDL->fenetrePrincipale);
      SDL_FreeSurface(message);

message = TTF_RenderText_Solid(structSDL->font, "Utilisez les touches E/R pour monter/descendre d'un niveau", structSDL->couleurTexte);
      blitteSurface(largeur/3, 640, message, structSDL->fenetrePrincipale);

      TTF_CloseFont(structSDL->font);
      SDL_FreeSurface(message);

      /* 3eme taille de police */
      structSDL->font = TTF_OpenFont(font,20);

      message = TTF_RenderText_Solid(structSDL->font, "Appuyez sur esc pour retourner au demarrage", structSDL->couleurTexte);
      blitteSurface(0, 0, message, structSDL->fenetrePrincipale);

      TTF_CloseFont(structSDL->font);
      SDL_FreeSurface(message);

      SDL_Flip(structSDL->fenetrePrincipale);


      /*===================== Boucle de d'évenements de la page des commandes ==================================*/

      while (SDL_PollEvent(&event))
	{
	  /*écoute des évenements*/
	  switch (event.type)
	    {

	    case SDL_VIDEORESIZE:
	      structSDL->largeurEcran = event.resize.w;
	      structSDL->hauteurEcran = event.resize.h;
	      miseAJourTailles(structSDL);
	      break;

	      /*les touches claviers sont scrutées*/
	    case SDL_KEYDOWN:
	      switch (event.key.keysym.sym)
		{

		  /*sortie si esc est pressé*/
		case SDLK_ESCAPE:
		  done = 1;
		  break;


		default:
		  break;

		}
	      break;

	  
	    } 
	}
  
    }
  SDL_FreeSurface(clicDroit);
  SDL_FreeSurface(clicGauche);
  SDL_FreeSurface(fleches);
  SDL_FreeSurface(ER);

}
static int affichePageDemarrage(StructSDL* structSDL)
{
  char done = 0;
  int hauteur, largeur;
  
  SDL_Surface* dem;
  SDL_Event event;
  
  char* font = "data/wonderland.ttf";
  SDL_Surface *message = NULL; 

  
  /*====================== Fond de la page de demarrage =====================*/

  dem = SDL_LoadBMP("data/demarrage.bmp");
  if (!dem)
    {
      printf("Unable to load bitmap: %s\n", SDL_GetError());
      return 1;
    }
  structSDL->pageDemarrage = SDL_DisplayFormat(dem);
  SDL_FreeSurface(dem);


  while(done == 0)
    {
      largeur = structSDL->largeurEcran/2;
      hauteur = structSDL->hauteurEcran/2;

      /*effacer l'écran*/
      SDL_FillRect(structSDL->fenetrePrincipale, 0, SDL_MapRGB(structSDL->fenetrePrincipale->format, 0, 0, 0));
  
      /* chargement image de fond */
      blitteSurface(0,0,structSDL->pageDemarrage,structSDL->fenetrePrincipale);


      /*========================= Texte de la page de demarrage ============================*/

      structSDL->font = TTF_OpenFont(font,200); 
      if( structSDL->font == NULL ) 
	{ 
	  printf("Erreur de chargement de la police de caractère %s",font); 
	} 
      structSDL->couleurTexte.r = 255;
      structSDL->couleurTexte.g = 255;
      structSDL->couleurTexte.b = 255;

      message = TTF_RenderText_Solid(structSDL->font, "Exil", structSDL->couleurTexte);
      if( message == NULL )
	{ 
	  printf("Erreur de chargement du texte\n"); 
	} 
      blitteSurface(largeur - 200, hauteur - 150, message, structSDL->fenetrePrincipale);
      TTF_CloseFont(structSDL->font);

      structSDL->font = TTF_OpenFont(font,30);
      SDL_FreeSurface(message);

      message = TTF_RenderText_Solid(structSDL->font, "Appuyez sur espace pour demarrer", structSDL->couleurTexte);
      blitteSurface( largeur - 215, hauteur + 25, message, structSDL->fenetrePrincipale);
      SDL_FreeSurface(message);

      message = TTF_RenderText_Solid(structSDL->font, "Appuyez sur tabulation pour voir l'aide", structSDL->couleurTexte);
      blitteSurface( largeur - 240, hauteur + 50, message, structSDL->fenetrePrincipale);
      SDL_FreeSurface(message);

      TTF_CloseFont(structSDL->font);

      SDL_Flip(structSDL->fenetrePrincipale);


      /*===================== Boucle de d'évenements de la page de démarrage ==================================*/

      while (SDL_PollEvent(&event))
	{
	  /*écoute des évenements*/
	  switch (event.type)
	    {
	      /*sortie si l'on clique sur la croix de fermeture*/
	    case SDL_QUIT:
	      done = 1;
	      return 1;
	      break;

	    case SDL_VIDEORESIZE:
	      structSDL->largeurEcran = event.resize.w;
	      structSDL->hauteurEcran = event.resize.h;
	      miseAJourTailles(structSDL);
	      break;

	      /*les touches claviers sont scrutées*/
	    case SDL_KEYDOWN:
	      switch (event.key.keysym.sym)
		{

		  /*sortie si esc est pressé*/
		case SDLK_ESCAPE:
		  done = 1;
		  return 1;
		  break;

		case SDLK_SPACE:
		  SDL_FreeSurface(structSDL->pageDemarrage);
		  done = 1;
		  break;

		case SDLK_TAB:
		  affichePageTouches(structSDL);
		  break;

		default:
		  break;

		}
	      break;

	  
	    } 
	}
  
    }
  return 0;
}

int bouclePrincipale(StructSDL* structSDL, Carte* carte)
{
  /*boucle principale*/
  char done = 0;
  char pageDemarrage = 0;
  FPSmanager fps;

  SDL_Surface* fd = NULL;
  SDL_Surface* col = NULL;
  SDL_Surface* ent = NULL;
  

  /*initialisation de la gestion des fps*/
  SDL_initFramerate(&fps);
  SDL_setFramerate(&fps,60);

  /* chargement des images*/

fd = SDL_LoadBMP("data/fond.bmp");
  if (!fd)
    {
      printf("Unable to load bitmap: %s\n", SDL_GetError());
      return 1;
    }
  structSDL->fond = SDL_DisplayFormat(fd);
  SDL_FreeSurface(fd);

  col = SDL_LoadBMP("data/colonne.bmp");
  if (!col)
    {
      printf("Unable to load bitmap: %s\n", SDL_GetError());
      return 1;
    }
  structSDL->colonne = SDL_DisplayFormat(col);
  SDL_FreeSurface(col);

 ent = SDL_LoadBMP("data/entete.bmp");
  if (!ent)
    {
      printf("Unable to load bitmap: %s\n", SDL_GetError());
      return 1;
    }
  structSDL->entete = SDL_DisplayFormat(ent);
  SDL_FreeSurface(ent);

  /*============================ Page de démarrage =======================*/

  pageDemarrage = affichePageDemarrage(structSDL);
  if(pageDemarrage == 1)
    return 0;



/*==========================debut de l'affichage de l'écran du jeu ==========================*/

  while (done == 0)
    {

      /*boucle d'evenement*/
      boucleEvenements(structSDL, carte, &done);


      /*effacer l'écran*/
      SDL_FillRect(structSDL->fenetrePrincipale, 0, SDL_MapRGB(structSDL->fenetrePrincipale->format, 0, 0, 0));

      /* chargement image de fond */
      blitteSurface(0,0,structSDL->fond,structSDL->fenetrePrincipale);
      blitteSurface(0,120,structSDL->colonne,structSDL->fenetrePrincipale);
      blitteSurface(0,0,structSDL->entete,structSDL->fenetrePrincipale);


      /*affichage de la carte*/
      afficheCarte(structSDL, carte);

      affichagePersonnages(structSDL, carte);

      /*affichage des textes*/
      affichageTextes(structSDL);

      /*fin de l'affichage*/

      /*mise en place d'un delai pour respecter les fpsmaxi*/
      SDL_framerateDelay(&fps);

      /*=============================mise à jour de l'affichage===========================*/
      SDL_Flip(structSDL->fenetrePrincipale);

      
      /*incremente les valeurs de la ville*/
      incrementePasDeTemps(structSDL->ville);

    } /*fin de la boucle principale*/

  TTF_Quit();

  /*réussite de la sortie du programme*/
  printf("Arret reussi\n");

  return 0;
}


int affichage()
{
  /*carte de test*/
  int valReturn, i;
  Carte* carte;
  StructSDL* structSDL;
  Ville* ville;
  TabTerrains tableauTerr;
  char *fichierDat = {"DatTerr"};

  tableauTerr = creerTabTerrains(fichierDat);
  carte = genererCarte(100,100,5,6,30,80,20,&tableauTerr);
  creerVille(&ville);
  creerStructSDL(&structSDL);

  for(i=0;i<10;i++)
    ajouterMembreVille(ville);

  structSDL->ville = ville;


  /* initialise SDL video*/
  /* on charge tout les susbsystem, en fonction des avancées ne charger que les indispensables. Possibilité d'utiliser int SDL_InitSubSystem(Uint32 flags) pour offrir leurs activation par le joueur via les options*/

  if ( SDL_Init( SDL_INIT_EVERYTHING) < 0 ) /* on charge tout les subsystem, en fonction des avancées ne charger que les indispensables. Possibilité d'utiliser int SDL_InitSubSystem(Uint32 flags) pour offrir leurs activation par le joueur via les options*/
    {
      printf( "Impossible d'initialiser SDL: %s\n", SDL_GetError() );
      return 1;
    }


  atexit(SDL_Quit);


  /* creation de la fenetre principale*/
  SDL_WM_SetCaption("Exil", NULL);

  structSDL->fenetrePrincipale = SDL_SetVideoMode(structSDL->largeurEcran, structSDL->hauteurEcran, structSDL->couleursEcran, SDL_HWSURFACE|SDL_DOUBLEBUF|SDL_RESIZABLE);


  if ( !structSDL->fenetrePrincipale)
    {
      printf("Unable to set 640x480 video: %s\n", SDL_GetError());
      return 1;
    }

 /*Initialisation de SDL_ttf*/
  if( TTF_Init() == -1)
    {
      printf("Erreur d'initialisation de la librairie SDL ttf\n");
      return 1;
    }


  /*======================= démarrage de la boucle principale ===========================*/
  valReturn = bouclePrincipale(structSDL, carte);
 
  detruireTabTerrains(&tableauTerr);
  detruireCarte(carte);
  detruireVille(ville);
  detruireStructSDL(structSDL);

  return valReturn;
}


void testAffichageSDL()
{
  affichage();
}
